import singleton from "./Singleton";
/**
 * 实现一个常驻计时器，用来支持在所有页面都需要轮询的业务
 */

type EventMapValue = {
	interval : number,
	handler : () => void
}

const eventNames = [
	'driver-checkHasAcceptOrders', //检测是否有车队派单或需要确认的派单通知，该事件进入司机应用内接单页面
	'driver-uploadPos', //上传司机坐标位置
	'driver-check-warn-msg',//司机端检测是否有警告信息
] as const;

type EventName = typeof eventNames[number]

class AppRunTimer {
	private timerId !:number; //计时器id
	private runTimeCount = 0;
	private eventMap = new Map<EventName, EventMapValue>();
	

	//开启计时
	start () {
		if (this.timerId) return;
		this.timerId = setInterval(() => {
			this.runTimeCount += 1;
			this.triggerEvent();
		}, 1 * 1000);
	};
	//暂停计时
	stop () {
		if (!this.timerId) return;
		clearInterval(this.timerId);
		this.timerId = 0;
	};
	
	on (name : EventName, ops : EventMapValue) {
		if (!eventNames.includes(name)) return; //同个事件只允许注册一次
		this.eventMap.set(name, ops);
	};
	
	off (name : EventName) {
		if (arguments.length === 0) return;
		this.eventMap.forEach((_, key) => {
			if (key === name) {
				this.eventMap.delete(name);
			};
		});
	};
	
	private triggerEvent () {
		for (const [ ,value] of this.eventMap) {
			if (this.enableTrigger(value)) {
				value.handler && value.handler();
			};
		};
	};
	
	/**
	 * 是否允许触发eventmap中的事件
	 * @returns {boolean}
	 */
	private enableTrigger (ops : EventMapValue) : boolean {
		if (!ops || ops.interval === void 0) return false;
		return this.runTimeCount % ops.interval === 0;
	}
}


const Single = singleton(AppRunTimer);
const appRunTimer = new Single();
export default appRunTimer;
